package com.example.supermonkeysm.utils;

import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

public class Utils {
    /**
     * 获取forEach下标
     */
    public static <T> Consumer<T> forEach(BiConsumer<T, Integer> consumer) {
        class IndexObject {
            int index;
        }
        IndexObject indexObject = new IndexObject();
        return i -> consumer.accept(i, indexObject.index++);
    }
    /**
     * Object转List
     */
    public static <T> List<T> castList(Object obj, Class<T> clazz){
        List<T> result = new ArrayList<>();
        if(obj instanceof List<?>){
            for (Object o : (List<?>) obj){
                result.add(clazz.cast(o));
            }
            return result;
        }
        return new ArrayList<>();
    }
    /**
     * 切换redisDB
     */
    public static RedisTemplate<String,Object> setDataBase(RedisTemplate<String, Object> redisTemplate, int db){
        LettuceConnectionFactory connectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
        if(connectionFactory != null && db != connectionFactory.getDatabase()){
            connectionFactory.setDatabase(db);
            redisTemplate.setConnectionFactory(connectionFactory);
            connectionFactory.resetConnection();
            connectionFactory.afterPropertiesSet();
        }
        return redisTemplate;
    }
}
